import 'package:flutter/material.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/pages/other/pixiv/search_pixiv.dart';

class PixivImage extends StatefulWidget {
  const PixivImage({super.key});

  @override
  State<PixivImage> createState() => _PixivImageState();
}

class _PixivImageState extends State<PixivImage> with TickerProviderStateMixin {
// 1. 状态变量优化：用 final 修饰控制器（引用不变）
  final TextEditingController controller = TextEditingController();
  final PageController pageController = PageController();
  late final TabController tabController; // 常量控制器用 late final
// 2. 用 ValueNotifier 管理搜索触发状态：避免直接 setState 导致全局重建
  final ValueNotifier<bool> _isSearchChanged = ValueNotifier(false);
  final ScrollController _scrollController = ScrollController();

// 3. 搜索提交逻辑：仅更新 ValueNotifier，不触发全局 setState
  void _handleSearchSubmitted(String value) {
    FocusScope.of(context).unfocus(); // 简洁失焦
    _isSearchChanged.value = !_isSearchChanged.value; // 仅更新 Notifier 值
  }

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    controller.dispose();
    pageController.dispose();
    tabController.dispose();
    _scrollController.dispose();
    _isSearchChanged.dispose(); // 释放 ValueNotifier
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

// 4. 全局重绘隔离：避免局部状态变化扩散到整个页面
    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text(''),
          toolbarHeight: 0,
          elevation: 0,
          leading: null,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
        ),
        body: Column(
          children: [
// 5. 搜索框独立封装：核心优化！隔离聚焦状态变化
            const RepaintBoundary(
              child: _SearchInputContainer(),
            ),
            Expanded(
// 6. 用 ValueListenableBuilder 包裹 SearchPixiv：仅当搜索状态变化时重建
              child: ValueListenableBuilder<bool>(
                valueListenable: _isSearchChanged,
                builder: (context, isChanged, child) {
                  return SearchPixiv(
                    tag: controller.text,
                    change: isChanged,
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 7. 搜索框独立组件：仅负责搜索框渲染，状态通过父组件获取
class _SearchInputContainer extends StatelessWidget {
  const _SearchInputContainer();

  @override
  Widget build(BuildContext context) {
// 安全获取父组件状态
    final parentState = context.findAncestorStateOfType<_PixivImageState>()!;

    return MySearchInput(
      controller: parentState.controller,
      onSubmitted: (v) => parentState._handleSearchSubmitted(v),
    );
  }
}
